#!/bin/bash

set -e

echo "Setting up Smart Snapshotter development environment..."

# Check Go version
GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
REQUIRED_VERSION="1.21"

if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$GO_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
    echo "Error: Go version $REQUIRED_VERSION or higher is required, found $GO_VERSION"
    exit 1
fi

echo "✓ Go version check passed: $GO_VERSION"

# Install development tools
echo "Installing development tools..."

# golangci-lint
if ! command -v golangci-lint &> /dev/null; then
    echo "Installing golangci-lint..."
    go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
fi

# air (for hot reload)
if ! command -v air &> /dev/null; then
    echo "Installing air..."
    go install github.com/cosmtrek/air@latest
fi

# goimports
if ! command -v goimports &> /dev/null; then
    echo "Installing goimports..."
    go install golang.org/x/tools/cmd/goimports@latest
fi

# Download dependencies
echo "Downloading Go dependencies..."
go mod download
go mod tidy

# Create necessary directories
echo "Creating project directories..."
mkdir -p logs tmp

# Set up git hooks (if in git repo)
if [ -d ".git" ]; then
    echo "Setting up git hooks..."
    mkdir -p .git/hooks

    # Pre-commit hook
    cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# Run linting before commit
make lint
if [ $? -ne 0 ]; then
    echo "Linting failed. Please fix the issues before committing."
    exit 1
fi
EOF
    chmod +x .git/hooks/pre-commit
fi

echo "✓ Development environment setup complete!"
echo ""
echo "Available commands:"
echo "  make build      - Build the binary"
echo "  make test       - Run tests"
echo "  make lint       - Run linter"
echo "  make dev        - Run with hot reload"
echo "  make help       - Show all available commands"